//
//  PPAvatarSettingPreviewViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/17/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAvatarSettingPreviewViewController.h"

#import "PPAvatarSettingPreviewActionView.h"

#import "PPNetworkService.h"

#import "PPImageTransaction.h"

#import "PPSettingNavBar.h"
@interface PPAvatarSettingPreviewViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (readwrite, nonatomic, strong) UIView *backgroundView;
@property (readwrite, nonatomic, strong) UIImageView *imageView;
@property (nonatomic,strong) PPSettingNavBar *settingNavBar;
@end

@implementation PPAvatarSettingPreviewViewController
- (PPSettingNavBar *)settingNavBar{

    if (!_settingNavBar) {
        _settingNavBar = [PPSettingNavBar settingNavbar];
        _settingNavBar.backgroundColor = BLACK;
        [_settingNavBar.midBtn setTitle:@"个人头像" forState:UIControlStateNormal];
        [_settingNavBar.midBtn setTitleColor:WHITE forState:UIControlStateNormal];

        if (IS_IOS_8) {
            _settingNavBar.midBtn.titleLabel.font = PFFontMedium(16);
        }else{
        _settingNavBar.midBtn.titleLabel.font = PPFONT(PFBold, 16);
        }
        
        
        [_settingNavBar.leftBtn setTitle:@"个人资料" forState:UIControlStateNormal];
        _settingNavBar.leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 16, 0, 0);
        _settingNavBar.leftBtn.titleLabel.font = PPFONT(PFMedium, 15);
        _settingNavBar.leftBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0,0);
        [_settingNavBar.leftBtn setTitleColor:WHITE forState:UIControlStateNormal];
        
        _settingNavBar.rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0,16);

    }
    return _settingNavBar;
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = NO;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
- (void)viewDidLoad {
    [super viewDidLoad];

//    self.title = @"个人头像";

    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"个人资料" image:@"nav_back" target:self action:@selector(popViewPreviousController)];
    
    self.view.backgroundColor = [UIColor blackColor];



    
    
    [self.view addSubview:self.settingNavBar];
    
    [self.settingNavBar.leftBtn addTarget:self action:@selector(popViewPreviousController) forControlEvents:UIControlEventTouchUpInside];
    
    if(!_editDiabled) {
        //        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-nav-more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreItemDidPressed:)];
        //
        //        self.navigationItem.rightBarButtonItem.tintColor = BLACK;
        
        [self.settingNavBar.rightBtn addTarget:self action:@selector(moreItemDidPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    _backgroundView = [[UIView alloc] init];
    _backgroundView.backgroundColor = [UIColor colorWithRGBHex:0xe5e5e5];
    [self.view addSubview:_backgroundView];

    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor clearColor];
    _imageView.contentMode = UIViewContentModeCenter;
    _imageView.clipsToBounds = YES;
    [_backgroundView addSubview:_imageView];

    [self reloadAvatar];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    
    
    CGFloat width = self.view.width;
    CGFloat height = width;
    
    self.settingNavBar.frame = CGRectMake(0, 0,SCREEN_WIDTH, 64);
    
//    _backgroundView.frame = CGRectMake(0,CGRectGetMaxY(self.settingNavBar.frame), width, height);
    
    _backgroundView.center = CGPointMake(self.view.center.x, self.view.center.y);
    _backgroundView.bounds = CGRectMake(0, 0, width, height);
    _imageView.frame = _backgroundView.bounds;
}

- (void)moreItemDidPressed:(UIButton *)item {
    PPAvatarSettingPreviewActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPAvatarSettingPreviewActionView" owner:nil options:nil].firstObject;
    actionView.frame = CGRectMake(0, self.navigationController.view.height - actionView.height, self.navigationController.view.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(self)weakSelf = self;
    __weak typeof(popoverView)weakPopover = popoverView;
    [actionView.cancelButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.cameraButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.delegate = weakSelf;
            [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.albumButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
              imagePickerController.navigationBar.tintColor = [UIColor blackColor];
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.delegate = weakSelf;
            [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    if(_avatar.length == 0) {
        actionView.saveButton.enabled = NO;
    } else {
        actionView.saveButton.enabled = YES;

        [actionView.saveButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.allowsEditing = YES;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.delegate = weakSelf;
                [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
//                PPAccountProfiles *profiles = [PPAccountManager sharedInstance].account.profiles;
//                if(profiles.avatarURLString.length == 0)
//                {
//                    [weakSelf.navigationController.view toastMessage:@"您还没有设置头像哦，请上传头像"];
//                    return ;
//                }
//
//                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.navigationController.view animated:YES];
//
//                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:weakSelf.avatar] options:kNilOptions progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
//
//                    dispatch_async(dispatch_get_main_queue(), ^{
//
//                        [hud hide:YES];
//
//                        if(error == nil) {
//                            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//                        } else {
//                            [weakSelf.navigationController.view toastMessage:error.networkPrompt];
//                        }
//                    });
//                }];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [popoverView displayAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
    UIImage *image = info[UIImagePickerControllerEditedImage] ? : info[UIImagePickerControllerOriginalImage];

    PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
    artwork.image = image;
    artwork.uuid = [NSString uuid];

    [picker dismissViewControllerAnimated:YES completion:^{

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        [[PPImageTransaction sharedInstance] prepareTransactionWithArtwork:artwork completion:^{

            __weak typeof(self)weakSelf = self;
            [PPNetworkService updateAvatarWithFileName:artwork.transactionIdentifier callback:^(id data, NSError *error) {

                __strong typeof(weakSelf)strongSelf = weakSelf;

                if(strongSelf == nil) {
                    return;
                }

                if(error == nil) {
                    NSString *key = [data validStringForKey:@"key"];
                    NSString *token = [data validStringForKey:@"uploadToken"];
                    NSString *host = [data validStringForKey:@"host"];

                    [[PPImageTransaction sharedInstance] beginTransactionWithIdentifier:artwork.transactionIdentifier key:key token:token completion:^(NSError *error) {
                        __strong typeof(weakSelf)strongSelf = weakSelf;

                        if(strongSelf == nil) {
                            return;
                        }

                        [hud hide:YES];

                        if(error == nil) {

                            PPAccountProfiles *profiles = [PPAccountManager sharedInstance].account.profiles;
                            profiles.avatar = key;
                            profiles.avatarHost = host;
                            [profiles.managedObjectContext saveContext];

                            strongSelf.avatar = profiles.avatarURLString;

                            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                            [userInfo setSafeObject:host forKey:@"avatarHost"];
                            [userInfo setSafeObject:key forKey:@"avatarKey"];

                            [[NSNotificationCenter defaultCenter] postNotificationName:PPAccountProfilesAvatarDidChangeNotification object:profiles.avatarURLString userInfo:userInfo];

                            [strongSelf.navigationController.view toastMessage:@"上传成功" duration:1];
                        } else {
                            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
                        }
                    }];
                    
                } else {
                    [hud hide:YES];
                    
                    [strongSelf.navigationController.view toastMessage:error.networkPrompt];
                }
            }];

        }];

    }];

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error) {
        if([[error domain] isEqualToString:ALAssetsLibraryErrorDomain] && [error code] == ALAssetsLibraryDataUnavailableError) {
            [self.navigationController.view toastMessage:@"保存失败"];
        }
    } else {
        [self.navigationController.view toastMessage:@"保存成功"];
    }
}

- (void)reloadAvatar {
    __weak typeof(self) weakSelf = self;

    if(_avatar.length > 0) {
        [_imageView sd_setImageWithURL:[NSURL URLWithString:_avatar] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if(image != nil) {
                weakSelf.imageView.contentMode = UIViewContentModeScaleAspectFill;
            }
        }];
    } else {
        _imageView.image = [UIImage imageNamed:@"person_normal"];
    }
}

- (void)setAvatar:(NSString *)avatar {
    _avatar = avatar;

    [self reloadAvatar];
}

@end
